{% extends "layout.html" %}
{% block title %}策略监控{% endblock %}
{% block head %}
  {{ super() }}
	<script src="http://cdn.bootcss.com/socket.io/1.5.1/socket.io.js"></script>
{% endblock %}
{% block content %}
<div>
            <form class="form-inline" role="form" id="loginFrom">
                <div class="form-group">
                    <label class="sr-only" for="name">名称</label>
                    <input type="text" class="form-control" name="name" id="name" placeholder="请输入名称">
                </div>
                <div class="form-group">
                    <label class="sr-only" for="pass">名称</label>
                    <input type="text" class="form-control" name="pass" id="pass"
                           placeholder="请输入名称">
                </div>
                <div class="form-group">
                    <select name="Futures" id="Futuresid" class="form-control">
                                            <option value ="中航期货">中航期货</option>
                                            <option value ="华泰期货" >华泰期货</option>
                                            <option value ="弘业期货">弘业期货</option>
                                            <option value ="simnow模拟" selected = "selected">simnow模拟</option>

                    </select>
                </div>
                <button type="button" class="btn btn-default" onclick="login()">登陆</button>
            </form>
        </div>

        <div>
                <br>

                <form class="form-inline" role="form" id="straForm">

                  <div class="form-group">
                            <select name="select_strategies" id="select_strategies" class="form-control" onchange="checkField(this.value)"></select>
                            <select name="select_instrument" id="select_instrument" class="form-control"></select>
                            <select name="select_mappinginstrument" id="select_mappinginstrument" class="form-control"></select>
                            <label for="zhouqi" class="form-control">周期</label>
                            <input type="text" class="form-control " name="zhouqi" id="zhouqi" placeholder="请输入周期">
                            <select name="select_IntervalType" id="select_IntervalType" class="form-control">
                                    <option value ="IntervalType.Second">秒</option>
                                    <option value ="IntervalType.Minute" selected = "selected">分</option>
                                    <option value ="IntervalType.Hour">时</option>
                                    <option value="IntervalType.Day">天</option>
                                    <option value="IntervalType.Week">周</option>
                                    <option value="IntervalType.Month">月</option>
                            </select>
                            <label for="name">参数</label>
                            <input type="text" class="form-control" name="canshuid" id="canshuid">
                  </div>

                    <button type="button" id='submitAdd' class="btn btn-default" onclick="submitAddFun()">提交</button>
                </form>
        </div>

        <hr>
        <button type="button" class="btn btn-default" onclick="allLoad()">加载全部</button>
        <button type="button" class="btn btn-default" onclick="alltrading()">启动全部</button>
        <button type="button" class="btn btn-default" onclick="window.open('{{ url_for('showPositionCheck')}}')">仓位检查</button>

        <div>
            <!--table-primary 表头标题变成绿色-->
            <table class="table table-bordered table-striped table-condensed table-hover table-primary" id="strateg">
		        <caption></caption>
		           <thead></thead>
		           <tbody></tbody>
	        </table>
        </div>

    <script type="text/javascript" charset="utf-8">
        var table_cols = {};

        //table_cols['position'] = new Array("策略", "商品", "映射商品", "周期", "参数", "交易", "交易状态", "当前理论仓位");
        table_cols['strateg'] = new Array("id", "Strategy", "Instrument","Mappinginstrument","Interval","IntervalType","Params",'加载','交易','显示k线','运行状态');
        var stras = {{stras|tojson}};           //得到所有策略实例
        var strageties={{ strageties|tojson }}  //得到所有策略类
        var allInstrument={{allInstrument|tojson}}//从数据库得到所有合约以及最小跳
        $(document).ready(function () {
			init_table('strateg');
            var seles = document.getElementById('select_strategies');  //加载所有策略类
			for(var i in strageties){

				seles.options.add(new Option(i, i)); //策略标识作为返回的值
			}
            checkField(seles.value);//默认选择一下

            seles = document.getElementById('select_instrument');  //加载合约
			for(var i=0; i<allInstrument.length; i++){
				seles.options.add(new Option($.trim(allInstrument[i]['_id'])), $.trim(allInstrument[i]['_id'])); //策略标识作为返回的值
			}

            seles = document.getElementById('select_mappinginstrument');  //加载合约
			for(var i=0; i<allInstrument.length; i++){
				seles.options.add(new Option($.trim(allInstrument[i]['_id'])), $.trim(allInstrument[i]['_id'])); //策略标识作为返回的值
			}


            for(var i=0;i<stras.length;i++) {     //加载所有策略实例
                    table_show('strateg', stras[i]);
                }

		});


        //对列名进行填充
        function init_table(table_name) {
			var cols = table_cols[table_name];

			//用html()或$("#xx")[0].innerHTML
			$("#"+table_name + " thead").html('<tr></tr>');
			var title = $("#"+table_name + " thead tr")
			for(var v in cols){
				title.append('<th>'+cols[v]+'</th>');
			}
		}
        //填充数据参数
		function table_show(table_name, data) {
			var cols = table_cols[table_name];
			var key = null;
			switch(table_name){
				case "strateg":
					key = data["id"];
					break;
			}
			//if(table_name=="trade")//order的id xxx|xx|xx 由于有|会导致bug//trade.TradeID去掉前空格否则报错
			var tr = $("#"+table_name + ' tbody').children("#"+key);
			if(tr.length == 0) {
				$("#"+table_name + ' tbody')[0].innerHTML += '<tr id="' + key + '"></tr>';
				tr = $("#"+table_name + " tbody #"+key);
				//添加数据行时设置格式
				for(var v in cols){
					var val = data[cols[v]];

					//用于对数组的添加例如参数等()
					if(typeof(val)=='object') {
					    var temp=''
                        for (var v in val) {
                            temp = temp + v + "="+val[v] + ',';
                        }
                        tr.append('<td id="' + cols[v] + '">' + temp + '</td>');
                        continue ;
                    }


                    if(cols[v]=='加载'){     //systemidvalue为参数

                        if (data['Loadstatus']=="true"){
                            strtemp="已加载"
                        }else{
                            strtemp="未加载"
                        }
					    temp='<span class="input-group-btn"><button id="loadid" onclick=loadstra(this) systemidvaule="'+ data["id"] +'" class="btn btn-default" type="button">'+strtemp+'</button></span>';
					    tr.append('<td id="' + cols[v] + '">' + temp + '</td>');
					    continue ;
                    }
                    if(cols[v]=='交易') {
                        if (data['Tringstatus'] == "true") {
                            strtemp = "停止"
                        } else {
                            strtemp = "启动"
                        }
                        temp = '<span class="input-group-btn"><button id="tradingid"  onclick=trading(this) systemidvaule="' + data['id'] + '" class="btn btn-default" type="button">' + strtemp + '</button></span>';
                        tr.append('<td id="' + cols[v] + '">' + temp + '</td>');
                        continue;
                    }

                    if(cols[v]=='显示k线'){
                        if (data['Loadstatus']=="true"){
                            strtemp = "显示k线"
                            temp='<span class="input-group-btn"><button id="showkid"  onclick=showk(this) systemidvaule="'+ data['id'] +'" class="btn btn-default" type="button">' + strtemp +'</button></span>';
                        }else{
                            temp='';
                        }

					    tr.append('<td id="' + cols[v] + '">' + temp + '</td>');
					    continue ;
                    }
                    if(cols[v]=='运行状态'){
					    tr.append('<td id="' + cols[v] + '">' + '' + '</td>');
					    continue ;
                    }
                    //用于对普通数据的添加
					if(typeof(val) == "number")// !isNaN(val)) //数字
						val = val.toFixed(2);
					tr.append('<td id="'+cols[v]+'">' + val + '</td>');
					//对于普通数据的css进行更改
					if(!isNaN(data[cols[v]])) //数字:右对齐
						tr.children("#"+cols[v]).css('text-align', 'right');

				}
			}
			else{  //进行修改
				tr = $("#"+table_name + " tbody #"+key);
				for(var v in cols){
					var val = data[cols[v]];
					if(typeof(val) == "number") //if(!isNaN(val)) //数字
						val = val.toFixed(2);
					tr.children("#"+cols[v]).first().text(val);
				}
			}
		}



        //选中select 之后改变后面相应的params
        function checkField(val1){
            $("#canshuid").val('');
            var temp='';
            for(var p in strageties[val1]){
                temp=temp+'"'+p+'"'+':'+strageties[val1][p]+',';
            }
            temp=temp.substring(0,temp.length-1);  //去除最后一个空格
            $("#canshuid").val("{"+temp+"}");
        }

         //实盘账户进行登录
        function login(){
           var data={}
            data = $('#loginFrom').serialize();
            $.post('login',data,function(result)
            {
                 if (result.code != 'success'){
                    alert("failed to create a new api.")
                 } else {
                    table_show('strateg', result.obj);
                 }
            });
        }
        //对策略进行提交
        function submitAddFun(){
{#            var select_strategies = $('select_strategies').val();#}
{#            var form_data=JSON.stringify({"data":'ss'});#}
            var data={}
            data = $('#straForm').serialize();
            $.post('straAdd',data,function(result)
            {
                 if (result.code != 'success'){
                    alert("failed to create a new api.")
                 } else {
                    table_show('strateg', result.obj);
                 }
            });
        }

        //加载策略
        function loadstra(var1){
            var temp =$(var1).attr("systemIdVaule");

            var data={}
            data={"straid":$(var1).attr("systemIdVaule")};
            $.post('loadstra',data,function(result)
            {
                if(result.code!='success'){
                    alert(result.code);
                }else{
                    $(var1).text("已加载");
                    $("#strateg #"+temp+" #显示k线").append('<span class="input-group-btn"><button id="showkid"  onclick=showk(this) systemidvaule="'+ temp +'" class="btn btn-default" type="button"> 显示k线</button></span>');

                }
            })
        }

         //加载全部
        function allLoad(){
            $.post('allLoad',function(result)
            {
                if(result.code!='success'){
                    alert(result.code);
                }
            });
        }

         //启动停止实盘
        function trading(var1){
            var data={}
            data={"straid":$(var1).attr("systemIdVaule")};
            if($(var1).text()=='启动') {
                action = 'trading'
            }else{
                action = 'stoptrading'
            }
            $.post(action,data,function(result)
            {
                if(result.code!='success'){
                    alert(result.code);
                }else{
                    if($(var1).text()=='启动'){
                        $(var1).text("停止");
                    }else{
                        $(var1).text("启动");
                    }
                }
            });
        }

        //启动全部实盘
        function alltrading(){
            $.post('alltrading',function(result)
            {
                if(result.code!='success'){
                    alert(result.code);
                }
            })
        }


        //显示k线
        function showk(var1){
            var data={}
            data=$(var1).attr("systemIdVaule");
            window.open("{{ url_for('showk',straid='') }}"+data);    //传参数 不会传   只用变相用这个方法了
        }

	</script>

{% endblock %}




